package mobi.yuanshen.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import org.apache.commons.codec.binary.Base64;

import java.io.File;

public class AliVODUtils {
    //您的AccessKeyId
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    //您的AccessKeySecret
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    private static String decodeBase64(String data) {
        return new String(Base64.decodeBase64(data));
    }

    //上传文件
    public static void uploadLocalFile(OSSClient ossClient, JSONObject uploadAddress, String localFile) {
        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");
        File file = new File(localFile);
        ossClient.putObject(bucketName, objectName, file);
    }

    //初始OSS客户端
    private static OSSClient initOssClient(JSONObject uploadAuth, JSONObject uploadAddress) {
        String endpoint = uploadAddress.getString("Endpoint");
        String accessKeyId = uploadAuth.getString("AccessKeyId");
        String accessKeySecret = uploadAuth.getString("AccessKeySecret");
        String securityToken = uploadAuth.getString("SecurityToken");
        return new OSSClient(endpoint, accessKeyId, accessKeySecret, securityToken);
    }
    //初始化VOD客户端、需要注意接入服务地址
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        // 根据点播接入服务所在的Region填写，例如：接入服务在上海，则填cn-shanghai；其他区域请参见存储说明。
        String regionId = "cn-shanghai";
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }
    //创建视频上传结果对象
    public static CreateUploadVideoResponse createUploadVideo(DefaultAcsClient vodClient,String vodFileName, String title) throws ClientException {
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        // 设置上传视频名称,这里也要包含扩展名哦
        request.setFileName(vodFileName);
        request.setTitle(title);
        //设置请求超时时间
        request.setSysReadTimeout(1000);
        request.setSysConnectTimeout(1000);
        return vodClient.getAcsResponse(request);
    }


    /**
     * 上传视频
     * @param localFile 本地文件路径
     * @param vodFileName 点播文件名称
     * @param title 视频标题
     * @return 视频ID
     */
    public static String uploadVideo (String localFile,String vodFileName, String title) {

        String videoId = null;
        try {
            CreateUploadVideoResponse createUploadVideoResponse = getCreateUploadVideoResponse(vodFileName, title);
            // 执行成功会返回VideoId、UploadAddress和UploadAuth
            videoId = createUploadVideoResponse.getVideoId();
            //解析拿到结果对象
            JSONObject uploadAuth = JSONObject.parseObject(decodeBase64(createUploadVideoResponse.getUploadAuth()));
            JSONObject uploadAddress = JSONObject.parseObject(decodeBase64(createUploadVideoResponse.getUploadAddress()));

            // 使用UploadAuth和UploadAddress初始化OSS客户端
            OSSClient ossClient = initOssClient(uploadAuth, uploadAddress);
            // 上传文件，注意是同步上传会阻塞等待，耗时与文件大小和网络上行带宽有关
            uploadLocalFile(ossClient, uploadAddress, localFile);
            System.out.println("上传成功 : " + videoId);
        } catch (Exception e) {
            System.out.println("上传失败 : " + e.getLocalizedMessage());
            return null;
        }
        return videoId;
    }

    /**
     * 获取上传视频的响应对象,该方法可以获取上传地址和凭证
     * @param vodFileName 点播文件名称
     * @param title 视频标题
     * @return 响应对象
     */
    public static CreateUploadVideoResponse getCreateUploadVideoResponse(String vodFileName, String title) throws ClientException {
        // 初始化VOD客户端并获取上传地址和凭证
        DefaultAcsClient vodClient = initVodClient(accessKeyId, accessKeySecret);
        //创建一个响应对象
        CreateUploadVideoResponse createUploadVideoResponse =
                createUploadVideo(vodClient, vodFileName, title);
        return createUploadVideoResponse;
    }

    /**
     * 获取视频播放凭证
     * @param videoId 视频ID
     * @param time 播放凭证有效期
     * @return 播放凭证
     */
    public static String getVideoPlayAuth (String videoId,Long time) {

        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai",
                accessKeyId,accessKeySecret);

        IAcsClient client = new DefaultAcsClient(profile);

        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();

        request.setVideoId(videoId);
        request.setAuthInfoTimeout(time != null ? time : 3600L);
        try {
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            System.out.println(response.getPlayAuth());
            return response.getPlayAuth();
        } catch (ServerException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
